package com.marisfrolg;

import com.marisfrolg.scan.annotation.MarisfrolgMapping;
import com.marisfrolg.scan.annotation.MarisfrolgMapping;
import com.marisfrolg.scan.dao.PermissionDao;
import com.marisfrolg.scan.service.PermissionService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class ScanAuthManager implements BeanPostProcessor {

    @Resource
    private PermissionService permissionService;

    @Value("${spring.application.name}")
    private String serviceName;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        Class<?> clazz = bean.getClass();

        RestController demo = clazz.getAnnotation(RestController.class);
        if (demo != null) {
            RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                MarisfrolgMapping marisfrolgMapping = method.getAnnotation(MarisfrolgMapping.class);
                String path = annotation.value()[0] + marisfrolgMapping.value()[0];
                System.out.println(annotation.name() + "---" + marisfrolgMapping.description() + "---" + path);

                PermissionDao permissionDao = new PermissionDao(annotation.value()[0], marisfrolgMapping.description(), path, serviceName, 1, annotation.name());
                PermissionDao permission = permissionService.getByUrl(path);
                if (permission == null) {
                    permissionService.save(permissionDao);
                } else {
                    permissionDao.setId(permission.getId());
                    permissionService.updateById(permissionDao);
                }
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    private void updatePermissions(PermissionDao dao, PermissionDao DB) {
        if (!dao.getCode().equals(DB.getCode()) || !dao.getUrl().equals(DB.getUrl())
                || !dao.getDescription().equals(DB.getDescription()) || !dao.getService().equals(DB.getService())
                || dao.getStatus() != DB.getStatus() || dao.getController().equals(DB.getController())) {
            dao.setId(DB.getId());
            permissionService.updateById(dao);
        }
    }

    @PostConstruct
    public void test() {
        permissionService.updateStatus2forbidden(serviceName);
    }


}